package cn.jdy.plugins.admin;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.Discuss;
import cn.jdy.plugins.service.BusinessService;
import cn.jdy.plugins.service.DiscussService;

/**
 * @author wuzhiliang
 * @title 商机信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/business")
public class BusinessCtrl extends BaseCtrl {

	@Autowired
	private BusinessService businessService;
	@Autowired
	private DiscussService discussService;

	/**
	 * 初始化 商机信息列表
	 *
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(Business business, String fromDate, String toDate, Integer s) {
		ModelAndView mv = new ModelAndView("/operate/businessList.jsp");
		if(s!=null) mv.addObject("msg", "保存成功！");
		mv.addObject("entity", business);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList", confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));//商品分类下拉列表
		return mv;
	}

	/**
	 * 查询
	 * @param business
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Business business, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", businessService.query(business, fromDate, toDate));
			Long count = businessService.count(business, fromDate, toDate);
			jsonMap.put("iTotalDisplayRecords", count);
			jsonMap.put("iTotalRecords", count);
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询错误", e);
		}
		return jsonMap;
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable String id) {
		ModelAndView mv = new ModelAndView("/operate/businessDetail.jsp");
		mv.addObject("data", this.businessService.find(id));
		mv.addObject("classList", confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));// 查询 分类树第一级(分类 pid为0)
		return mv;
	}

	/**
	 * 查询品类
	 * @param bo
	 * @return
	 */
	@RequestMapping("/queryPinlei")
	@ResponseBody
	public Map<String, Object> queryPinlei(ConfValue bo) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("pinleiList", confService.find("pid", bo.getPid()));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "查询品类异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 批量更新
	 * @return
	 */
	@RequestMapping("/updBatch/{type}")
	@ResponseBody
	public Map<String, Object> updBatch(@PathVariable char type, @RequestParam(value = "id[]", defaultValue = "") List<String> id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			businessService.update(type, id);
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "商机信息更新异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 更新S币
	 * @return
	 */
	@RequestMapping("/updMoney")
	@ResponseBody
	public Map<String, Object> updMoney(String ids, int money) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			String[] id = ids.split(",");
			for(String s : id) {
				Business bo = businessService.queryById(s);
				if(bo != null && bo.getCreater() != null && bo.getCreater().length() > 0) {
					memberService.updateMoneyWithInfo(bo.getCreater(), money, "商机审核通过", "恭喜，您的商机被审核通过，赠送"+money+"S币");
				}
			}
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "商机信息更新异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 更新
	 * @param entity
	 * @return
	 */
	@RequestMapping("/update")
	public ModelAndView update(Business entity, @RequestParam(value="pinleiId") Long[] pinleiId) {
		ModelAndView mv = new ModelAndView();
		try {
			Set<ConfValue> set = new HashSet<>();
			for(Long id : pinleiId) {
				ConfValue cv = confService.find(id);
				if(cv!=null) set.add(cv);
			}
			entity.setbPinlei(set);
			entity.setUpdateTime(DateUtil.getCurrentTime());
			this.businessService.updateWithValidator(entity);

			mv.addObject("s", 200);
			mv.setViewName("redirect:/business/list");
		} catch(Exception e) {
			mv.setViewName("/business/edit/".concat(entity.getId()));
			BaseLog.e(getClass(), "商机信息更新异常！", e);
		}
		return mv;
	}

	/**
	 * 查询评论
	 * @param discuss
	 * @return
	 */
	@RequestMapping("/queryDis")
	@ResponseBody
	public Map<String, Object> queryDis(Discuss discuss) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", discussService.find("businessId", discuss.getBusinessId()));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询评论错误", e);
		}
		return jsonMap;
	}

	/**
	 * 商机回复
	 * @param entity
	 * @return
	 */
	@RequestMapping("/saveDis")
	@ResponseBody
	public Map<String, Object> saveDis(Discuss entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			entity.setUserId(getUser().getId());
			entity.setCreateTime(DateUtil.getCurrentTime());
			this.discussService.save(entity);
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "商机信息更新异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 下载订单
	 *
	 * @return
	 */
	@RequestMapping("/downExcel")
	public void downExcel(Business business, String fromDate, String toDate, HttpServletResponse response) {
		List<Business> list = businessService.query(business, fromDate, toDate);
		for(Business o : list) {
			String s;
			switch(o.getStatus()) {
				case "0": s = "待审核"; break;
				case "1": s = ("1".equals(o.getIsRecommend())) ? "推荐" : "审核通过"; break;
				case "2": s = "下架"; break;
				default: s = ""; break;
			}
			o.setStatus(s);
		}
		String[] titles = new String[]{"登记时间", "状态", "地区", "分类", "开业时间", "姓名", "电话", "面积", "资金", "上传者"};
		String[][] fieldNames = new String[][]{{"createTime"}, {"status"}, {"province", "city", "county", "address"},
				{"bClass.value0"},{"opeanDate"}, {"userName"}, {"telephone"}, {"acreage"}, {"inmoney"}, {"member.userName"}};
		super.downExcel(list, titles, fieldNames, "商机信息", response);
	}

}
